
//
//  CustomSearchView.swift
//  Exchange
//
//  Created by rui on 2018/7/6.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

protocol CustomSearchViewDelegate: class {
    func searchViewCancelClick()
    func searchViewSearch(text: String)
}

class CustomSearchView: UIView {

    lazy var searchInputView: UITextField = {
        let textField = UITextField()
        textField.returnKeyType = .search
        let icon = UIImageView(image: #imageLiteral(resourceName: "search"))
        icon.contentMode = .center
        icon.frame = CGRect(x: 0, y: 0, width: 30, height: 30 )
        textField.backgroundColor = UIColor(hexStr: "#fdfdfd")
        textField.leftViewMode = .always
        textField.font = UIFont.systemFont(ofSize: 14)
        textField.placeholder = kText("搜索")
        textField.leftView = icon
        textField.clearButtonMode = .whileEditing
        textField.delegate = self
        textField.layer.cornerRadius = 15
        textField.layer.masksToBounds = true
        textField.layer.borderWidth = 0.5
        textField.layer.border = ThemeManager.ThemeColorKeys.borderColor
        return textField
    }()
    
    lazy var cancel: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle(kText("取消"), for: .normal)
        btn.themeSetTitleColor(ThemeManager.ThemeColorKeys.text1, for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        btn.addTarget(self, action: #selector(cancelClick), for: .touchUpInside)
        return btn
    }()
    
    weak var delegate: CustomSearchViewDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        searchInputView.frame = CGRect(x: 0, y: (self.height - 30) * 0.5, width: self.width - 50, height: 30)
        cancel.frame = CGRect(x: searchInputView.right, y: 0, width: 50, height: self.height)
        self.addSubview(searchInputView)
        self.addSubview(cancel)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    @objc func cancelClick() {
        self.delegate?.searchViewCancelClick()
    }
}

extension CustomSearchView: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.delegate?.searchViewSearch(text: textField.text ?? "")
        return true
    }
}
